package de.kf.expenses.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DbAdapter
{

	// Database fields
	public static final String KEY_ROWID = "_id";

	/*
	 * public static final String KEY_CATEGORY = "category"; public static final
	 * String KEY_SUMMARY = "summary"; public static final String
	 * KEY_DESCRIPTION = "description"; private static final String
	 * DATABASE_TABLE = "todo";
	 */
	public static final String KEY_DATE = "date";
	public static final String KEY_AMOUNT = "amount";
	public static final String KEY_PURPOSE = "purpose";
	private Context context;
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;

	public DbAdapter(Context context)
	{
		this.context = context;
	}

	public DbAdapter open() throws SQLException
	{
		dbHelper = new DatabaseHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}

	public void close()
	{
		dbHelper.close();
	}

	/**
	 * Create a new todo If the todo is successfully created return the new
	 * rowId for that note, otherwise return a -1 to indicate failure.
	 */
	public long createTodo(String date, String amount, String purpose)
	{
		ContentValues initialValues = createContentValues(date, amount, purpose);

		return database.insert(Constants.DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Update the expense
	 */
	public boolean updateTodo(long rowId, String date, String amount,
			String purpose)
	{
		ContentValues updateValues = createContentValues(date, amount, purpose);

		return database.update(Constants.DATABASE_TABLE, updateValues,
				KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Deletes todo
	 */
	public boolean deleteTodo(long rowId)
	{
		return database.delete(Constants.DATABASE_TABLE, KEY_ROWID + "="
				+ rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all todo in the database
	 * 
	 * @return Cursor over all notes
	 */
	public Cursor fetchAllTodos()
	{
		return database.query(Constants.DATABASE_TABLE, new String[]
		{ KEY_ROWID, KEY_DATE, KEY_AMOUNT, KEY_PURPOSE }, null, null, null,
				null, null);
	}

	/**
	 * Return a Cursor positioned at the defined todo
	 */
	public Cursor fetchTodo(long rowId) throws SQLException
	{
		Cursor mCursor = database.query(true, Constants.DATABASE_TABLE,
				new String[]
				{ KEY_ROWID, KEY_DATE, KEY_AMOUNT, KEY_PURPOSE }, KEY_ROWID
						+ "=" + rowId, null, null, null, null, null);
		if (mCursor != null)
		{
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	private ContentValues createContentValues(String category, String summary,
			String description)
	{
		ContentValues values = new ContentValues();
		values.put(KEY_DATE, category);
		values.put(KEY_AMOUNT, summary);
		values.put(KEY_PURPOSE, description);
		return values;
	}
}
